


//
//  HomeSearchDemandTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/26.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "HomeSearchDemandTabVC.h"
#import "DemandCell.h"
#import "DemandOnlineOfflineCell.h"
#import "SearchConditionCell.h"
#import "HomeModel.h"
@interface HomeSearchDemandTabVC ()<DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,DemandCellDelegate,SearchConditionCellDelegate>
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,assign) NSInteger tag;
@property(nonatomic,assign) int index;
@end
@implementation HomeSearchDemandTabVC

- (void)viewDidLoad {
    [super viewDidLoad];
     self.manager = [AFHTTPSessionManager manager];
    self.pageNum = 1;
    self.pageSize = 10;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectDemandByTime:) name:@"selectDemandByTime" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectDemandByComment:) name:@"selectDemandByComment" object:nil];
    XLog(@"demandArray:%@",_demandArray);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.demandArray.count?self.demandArray.count+1:0;
}
- (void)setDemandArray:(NSMutableArray *)demandArray
{
    _demandArray = demandArray;
    XLog(@"首页搜索需求demandArray.count:%ld",demandArray.count);
    if (!demandArray.count) {
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
    }else {
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
        self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
        if (demandArray.count< 10) {
            footer.state = MJRefreshStateNoMoreData;
        }
    }
    [self.tableView reloadData];
}
- (void)setText:(NSString *)text
{
    _text = text;
}
-(void)reloadMore
{
    self.pageNum ++;
    if (self.tag == 1) {
        self.urlString = [NSString stringWithFormat:@"%@/demand/selectDemandByTime",kUrl];
    }else {
        self.urlString = [NSString stringWithFormat:@"%@/demand/selectDemandByComment",kUrl];
    }
        self.dict = @{
                      @"pageNumber":[NumberSwitchString numberSwitchString:self.pageNum],
                      @"pageSize":[NumberSwitchString numberSwitchString:self.pageSize],
                      @"content":self.text,
                      @"uid":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        XLog(@"self.dict:%@",self.dict);
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"reloadMore:%@",responseObject);
            NSArray *temp = [responseObject objectForKey:@"date"];
            if (temp.count) {
                for (NSDictionary *dict in temp) {
                    HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                    [self.demandArray addObject:model];
                }
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }else {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            XLog(@"error:%@",error);
        }];
    
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
-(void)reloadInternetData
{
    [self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.row == 0) {
        SearchConditionCell *cell = [SearchConditionCell cellNibWithTableView:tableView];
        cell.delegate = self;
        return cell;
    }else {
        DemandCell *cell = [DemandCell cellNibWithTableView:tableView];
        cell.delegate = self;
        cell.indexPath = indexPath;
        HomeModel *model = self.demandArray[indexPath.row-1];
        cell.homeModel = model;
        return cell;
        
    }
    
}
#pragma mark-代理:时间,评价排序
- (void)searchConditionCell:(SearchConditionCell *)searchConditionCell withTag:(NSInteger )tag
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    self.tag = tag;
    if (tag == 1) {
        self.index = 69;
    }else {
        self.index = 71;
    }
    self.dict = @{
                  @"pageNumber":[NumberSwitchString numberSwitchString:self.pageNum],
                  @"pageSize":[NumberSwitchString numberSwitchString:self.pageSize],
                  @"content":self.text,
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken]
                  };
    XLog(@"self.dict:%@",self.dict);
    XLog(@"self.index:%d",self.index);
    [CustomeManager POSTWithURLIndex:self.index parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark-代理:按时间评价
-(void)selectDemandByTime:(NSNotification *)info
{
    NSArray *temp = [info.userInfo objectForKey:@"date"];
    XLog(@"temp:%@",temp);
    self.demandArray = [NSMutableArray array];
    if (temp.count) {
        for (NSDictionary *dict in temp) {
            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
            [self.demandArray addObject:model];
        }
        [self.tableView reloadData];
        
    }
    [WSProgressHUD dismiss];
    
}
-(void)selectDemandByComment:(NSNotification *)info
{
    NSArray *temp = [info.userInfo objectForKey:@"date"];
    XLog(@"temp:%@",temp);
    self.demandArray = [NSMutableArray array];
    if (temp.count) {
        for (NSDictionary *dict in temp) {
            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
            [self.demandArray addObject:model];
        }
        [self.tableView reloadData];
    }
    [WSProgressHUD dismiss];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
        LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
        MainNavC *mainNav = [[MainNavC alloc]initWithRootViewController:logVC];
        [viewController presentViewController:mainNav animated:YES completion:nil];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
//                clickBtn.selected = !clickBtn.selected;
                XLog(@"clickBtn.selected:%d",clickBtn.selected);
                HomeModel *model = self.demandArray[indexPath.row-1];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
    
}
#pragma mark-代理:收藏
- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else{
        
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                clickBtn.selected = !clickBtn.selected;
                NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
                NSString *status = [NSString stringWithFormat:@"%d",clickBtn.selected];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"1",
                              @"status":status,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                [CustomeManager POSTWithURLIndex:34 parameters:self.dict success:^(NSDictionary *dict) {
                } failure:^(NSError *error) {
                }];
                
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 44;
    }else {
        return 144;
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0) {
        if (self.returnValueBlock) {
            self.returnValueBlock(indexPath.row);
        };
    }
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}
@end
